//
//  LoginSingleton.m
//  CleanerAir_Project
//
//  Created by 付亚杰 on 16/6/12.
//  Copyright © 2016年 Beijing Colin El Internet. All rights reserved.
//

#import "LoginSingleton.h"
#import "LocalDataHelpManager.h"
#import "CoreNewFeatureVC.h"
#import "SHLoginCMSModle.h"


static LoginSingleton *loginSingleton;
@implementation LoginSingleton

+ (instancetype)sharedLoginSingleton{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        loginSingleton = [[LoginSingleton alloc] init];
    });
    return loginSingleton;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        
        self.token = @"";
        self.cuid = @"";
        
        //判断APP 是否是第一次登录  启动轮播图，用户引导用到
        self.isFirstStart = [CoreNewFeatureVC canShowNewFeature];
        
        //获取登录状态
        _loginModel = [[CALoginModel alloc] init];
        NSDictionary *dic = [LocalDataHelpManager readToLocalwithPatch:loginCacheFolderName dateName:@"login"];
        if (dic != nil) {
            [_loginModel setValuesForKeysWithDictionary:dic];
            [_loginModel setValuesForKeysWithDictionary:dic[@"date"]];
            [_loginModel setValuesForKeysWithDictionary:dic[@"date"][@"member"]];
            self.token = self.loginModel.login_token;
            
            [[SHLoginCMSModle shareInstence]connectCMSgetName:[[NSUserDefaults standardUserDefaults] stringForKey:@"userName"] getPaw:[[NSUserDefaults standardUserDefaults] stringForKey:@"password"] sendBlcok:^(id obj) {
                if (obj != nil) {
                    
                    self.cuid = [NSString stringWithFormat:@"%ld",((NSNumber *)obj).integerValue];
                }
            }];
        }
        
        
        
        //监听网络
        // 1.获得网络监控的管理者
        AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
        // 2.设置网络状态改变后的处理
        [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            
            switch (status) {
                case AFNetworkReachabilityStatusUnknown: // 未知网络
                    self.netWorkStatus = Unknown;
                    break;
                    
                case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                    
                    [ShowMessage showCenterViewMessage:@"检测到网络断开，请检查网络"];
                    
                    self.netWorkStatus = NotReachable;
                    break;
                    
                case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                    self.netWorkStatus = ReachableViaWWAN;
                    break;
                    
                case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                    self.netWorkStatus = ReachableViaWiFi;
                    break;
            }
        }];
        // 3.开始监控
        [mgr startMonitoring];
        //获取当前网络状态
        [self changeNetworkState];
    }
    
    return self;
}


#pragma mark - 获取联网状态

- (void)changeNetworkState{
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    // 2.设置网络状态改变后的处理
    switch (mgr.networkReachabilityStatus) {
        case AFNetworkReachabilityStatusUnknown: // 未知网络
            self.netWorkStatus = Unknown;
            break;
            
        case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
            self.netWorkStatus = NotReachable;
            break;
            
        case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
            self.netWorkStatus = ReachableViaWWAN;
            break;
            
        case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
            self.netWorkStatus = ReachableViaWiFi;
            break;
    }
}

#pragma mark -- 登录成功
- (void)loginSuccess:(NSDictionary *)responseObject{
    
    [LocalDataHelpManager writeToLocalWithPatch:loginCacheFolderName dateName:@"login" data:responseObject];
    if (self.loginModel == nil) {
        self.loginModel = [[CALoginModel alloc] init];
    }
    
    NSLog(@"%@",responseObject);
    
    [self.loginModel setValuesForKeysWithDictionary:responseObject];
    [self.loginModel setValuesForKeysWithDictionary:responseObject[@"date"]];
    [self.loginModel setValuesForKeysWithDictionary:responseObject[@"date"][@"member"]];
    
    self.token = self.loginModel.login_token;
    NSLog(@"%@",self.token);
}

#pragma mark -- 退出登录
- (BOOL)loginOut{
    
    self.token = @"";
    self.loginModel = nil;
    self.perInfoModel = nil;
    
    BOOL isSuccess = [LocalDataHelpManager deleteFileWithPath:loginCacheFolderName dataName:@"login"];
    
    if (isSuccess) {
        [ShowMessage showCenterViewMessage:@"退出成功"];
    }else{
        [ShowMessage showCenterViewMessage:@"退出失败"];
    }
    
    return isSuccess;
}

#pragma mark -- 本地推送
// 取消某个本地推送通知
+ (void)cancelLocalNotificationWithKey:(NSString *)key{
    // 获取所有本地通知数组
    NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
    
    for (UILocalNotification *notification in localNotifications) {
        NSDictionary *userInfo = notification.userInfo;
        if (userInfo) {
            // 根据设置通知参数时指定的key来获取通知参数
            NSString *info = userInfo[key];
            
            // 如果找到需要取消的通知，则取消
            if (info != nil) {
                [[UIApplication sharedApplication] cancelLocalNotification:notification];
                break;
            }
        }
    }
}

#pragma mark -- 获取个人信息
- (void)getPerserInfoWithsuccess:(void (^)(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject))success failure:(void (^)(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error))failure{
    
    __weak __typeof(self) weakSelf = self;
    
    NSString *urlStr = [NSString stringWithFormat:@"/Api/Member/info?login_token=%@&member_id=%@",self.token,self.loginModel.ids];
    
    [HTTPManager get:GET_URLString(urlStr) success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject[@"msg"] isEqualToString:@"成功"]) {
            
            PersonalInformationModel *model = [[PersonalInformationModel alloc] init];
            [model setValuesForKeysWithDictionary:responseObject[@"date"]];
            
            //            给单例赋值
            weakSelf.perInfoModel = model;

        }
        
        success(operation,responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failure(operation,error);
    }];
}

@end
